package main

import (
	"bufio"
	"chat-client-demo/command"
	"log"
	"net"
	"os"
	"time"

	"google.golang.org/protobuf/proto"
)

const (
	ServerAddr = "127.0.0.1:12138"
	ServerId   = -1
)

var (
	cmder        = command.Commands{}
	userId int64 = 0
	conn   net.Conn
)

func main() {
	var err error
	conn, err = net.Dial("tcp", ServerAddr)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = conn.Close()
	}()

	log.Printf("chat server connect %s", conn.RemoteAddr())

	go func() {
		for {
			response, err := Decode(conn)
			if err != nil {
				log.Printf("ClientDecode error, %v", err)
			}
			msg := &Message{}
			_ = proto.Unmarshal(response.Data, msg)

			methods := map[CommandType]func(msg *Message){
				CommandType_HEARTBEAT:  heartbeat,
				CommandType_LOGIN_RESP: loginResp,
				CommandType_SEQ_RESP:   seqResp,
				CommandType_MSG_ACK:    msgAck,
				CommandType_MSG_NOTIFY: msgNotify,
			}

			methods[msg.Cmd](msg)
		}
	}()

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		input := scanner.Text()
		cmder.RunCommand(input)
	}
}

// 心跳处理
func heartbeat(msg *Message) {
	tickMsg := &Message{
		From: userId,
		To:   msg.From,
		Cmd:  CommandType_HEARTBEAT,
	}
	tickMsgData, _ := proto.Marshal(tickMsg)
	pbData, err := Encode(tickMsgData)
	if err != nil {
		panic(err)
	}
	_, _ = conn.Write(pbData)
}

// 获取消息ID
func seq() {
	seqMsg := &Message{
		From:       userId, // 此时应该不知道userId
		To:         ServerId,
		Cmd:        CommandType_SEQ_REQ,
		CreateTime: time.Now().UnixNano() / 1e6,
	}
	seqMsgData, _ := proto.Marshal(seqMsg)
	pbData, err := Encode(seqMsgData)
	if err != nil {
		panic(err)
	}
	_, _ = conn.Write(pbData)
}
